package serial

import (
	"got/socket"
	"time"
)

type TransServer struct {
	g    *GPRS
	sev  *socket.Server
	stop bool
}

//透明服务
//com=at串口地址
//btl=波特率
//listenAddr=服务监听地址
//transHost=需要透传到远端服务器的地址
//transPort=需要透传到远端服务器的端口
//closeReconnectTime=断开重连时间

func NewTransServer(com string, btl int, transHost, transPort string) (t *TransServer, e error) {
	o := new(TransServer)
	o.g, e = OpenGPRS(com, btl)
	if e != nil {
		return nil, e
	}
	//只保证一个连接
	var onlyConn *socket.Conn
	o.sev = socket.NewServer(0)
	o.sev.OnConnect(func(c *socket.Conn, bt []byte) []byte {
		debug("这里收到连接<<<<<<<<<<<<<<<<<<<<<<")
		if o.stop {
			c.Close()
			return []byte("err")
		}
		if onlyConn != nil && c.GetId() != onlyConn.GetId() {
			onlyConn.Close()
		}
		onlyConn = c
		res := make(chan bool)
		go func() {
			o.g.OnConnect(func() {
				//debug("这里连接成功<<<<<<<<<<<<<<<<<<<<<<", string(bt))
				o.g.Write(bt)
				res <- true
			})
			o.g.OnMessage(func(bt []byte) {
				c.Write(bt)
			})
			o.g.OnClose(func() {
				debug("这里关闭了连接<<<<<<<<<<<<<<<<<<<<<<")
				c.Close()
			})
			o.g.OnError(func(e error) {
				c.Close()
			})
			o.g.OpenTrans(transHost, transPort)
		}()
		ret := []byte("err")
		select {
		case <-res:
			ret = []byte("succ")
		case <-time.After(time.Second * 60):
			time.AfterFunc(time.Second*1, func() {
				debug("超时关闭<<<<<<<<<<<<<<<<<<<<<<")
				c.Close()
			})
			ret = []byte("err")
		}
		return ret
	})
	o.sev.OnMessage(func(c *socket.Conn, bt []byte) {
		o.g.Write(bt)
	})
	o.sev.OnClose(func(c *socket.Conn) {

	})
	o.sev.OnError(func(c *socket.Conn, e socket.Error) {
		c.Close()
	})
	return o, nil
}

func (this *TransServer) Listen(listenAddr string) error {
	return this.sev.Listen(listenAddr)
}

func (this *TransServer) GPRS() *GPRS {
	return this.g
}

func (this *TransServer) Stop() {
	this.stop = true
	this.sev.EachConn(func(c *socket.Conn) {
		c.Close()
	})
	go this.g.CloseTrans() //调试模式下关闭透传
}
